<template>
  <el-dialog
    v-model="visible"
    title="全站仪数据导入"
    width="60%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <el-alert
      title="支持选择文件夹或多选文件。系统将自动筛选出 .dat, .txt, .log, .csv4d 格式的文件。"
      type="info"
      show-icon
      :closable="false"
    />

    <div class="dialog-content">
      <el-form label-width="100px" class="form-section">
        <el-form-item label="选择数据源">
          <el-button @click="handleSelectFiles" type="primary" plain>
            <el-icon><Document /></el-icon>&nbsp;选择文件
          </el-button>
          <el-button @click="handleSelectFolder" type="success" plain>
            <el-icon><FolderOpened /></el-icon>&nbsp;选择文件夹
          </el-button>
        </el-form-item>
      </el-form>

      <div class="file-list-section">
        <div v-if="dataSourceInfo" class="source-info">{{ dataSourceInfo }}</div>

        <el-table v-if="filteredFiles.length > 0" :data="filteredFiles" border height="250" style="width: 100%">
          <el-table-column type="index" label="#" width="50" />
          <el-table-column prop="name" label="文件名" />
          <el-table-column prop="size" label="大小" width="120">
            <template #default="{ row }">
              {{ formatBytes(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastModified" label="修改日期" width="200">
            <template #default="{ row }">
                {{ new Date(row.lastModified).toLocaleString() }}
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else-if="dataSourceInfo" description="未找到符合条件的数据文件" />
      </div>
    </div>

    <input
      ref="fileInput"
      type="file"
      multiple
      style="display: none"
      @change="handleFileChange"
    />
    <input
      ref="folderInput"
      type="file"
      webkitdirectory
      directory
      style="display: none"
      @change="handleFolderChange"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm" 
          :loading="isLoading"
          :disabled="filteredFiles.length === 0"
        >
          确定导入
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage } from 'element-plus';
// 引入图标
import { Document, FolderOpened } from '@element-plus/icons-vue';

// --- state ---
const visible = ref<boolean>(false);
const isLoading = ref<boolean>(false);
const dataSourceInfo = ref<string>(""); // 用于显示数据来源信息
const allFiles = ref<File[]>([]); // 存储所有选中的文件
const fileInput = ref<HTMLInputElement | null>(null); // 新增：文件选择器的引用
const folderInput = ref<HTMLInputElement | null>(null);

const emit = defineEmits(['confirm']);

// --- computed ---

const filteredFiles = computed(() => {
  // 5. 新增 .csv4d 支持
  const allowedExtensions = ['.dat', '.txt', '.log', '.csv4d']; 
  return allFiles.value
    .filter(file => {
      const fileName = file.name.toLowerCase();
      return allowedExtensions.some(ext => fileName.endsWith(ext));
    })
    .map(file => ({
      name: file.name,
      size: file.size,
      lastModified: file.lastModified,
      raw: file
    }));
});

// --- methods ---

const formatBytes = (bytes: number, decimals = 2) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

// 6. 新增：触发文件选择
const handleSelectFiles = () => {
  fileInput.value?.click();
};

const handleSelectFolder = () => {
  folderInput.value?.click();
};

// 7. 新增：处理多文件选择的回调
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files) {
    allFiles.value = Array.from(input.files);
    dataSourceInfo.value = `已选择 ${allFiles.value.length} 个文件`;
  }
};

const handleFolderChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    allFiles.value = Array.from(input.files);
    const path = allFiles.value[0].webkitRelativePath;
    const folderName = path ? path.split('/')[0] : "一个文件夹";
    dataSourceInfo.value = `已从文件夹 [${folderName}] 中选择 ${allFiles.value.length} 个文件`;
  } else {
    allFiles.value = [];
    dataSourceInfo.value = "";
  }
};

const handleConfirm = async () => {
  if (filteredFiles.value.length === 0) {
    ElMessage.warning("没有可导入的有效文件");
    return;
  }
  isLoading.value = true;
  try {
    const filesToImport = filteredFiles.value.map(f => f.raw);
    await emit('confirm', {
      sourceInfo: dataSourceInfo.value,
      files: filesToImport
    });
    close();
  } catch (error) {
    console.error("Import failed:", error);
    ElMessage.error("导入失败，详情请查看控制台");
  } finally {
    isLoading.value = false;
  }
};

const open = () => {
  // 重置所有状态
  dataSourceInfo.value = "";
  allFiles.value = [];
  isLoading.value = false;
  // 清空<input>的值，确保下次选择相同文件/文件夹也能触发change事件
  if (fileInput.value) fileInput.value.value = '';
  if (folderInput.value) folderInput.value.value = '';
  visible.value = true;
};

const close = () => {
  visible.value = false;
};

defineExpose({ open, close });
</script>

<style scoped>
.dialog-content {
  padding: 0 20px;
}
.form-section {
  margin-top: 20px;
}
.file-list-section {
  margin-top: 15px;
}
.source-info {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
  background-color: #f4f4f5;
  padding: 8px 12px;
  border-radius: 4px;
}
</style>